<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      textarea {
        width: 500px;
        height: 100px;
      }
      .text {
        width: 500px;
        background-color: rgb(214, 236, 255);
        display: flex;
        justify-content: space-between;
      }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <textarea style="resize: none" placeholder="请输入评论"></textarea><br />
    <button id="btn">发布评论</button>

    <script>
      $(document).ready(function () {
        $("#btn").click(function () {
          var tArea = $("textarea").val();
          var box = $("<div>", { class: "text" }).html(`
            <span>${tArea}</span>
            <div>
              <button>编辑</button>
              <a class="del">删除</a>
            </div>
          `);
          $("body").append(box);

          $("body").on("click", ".del", function () {
            if (confirm("确定删除吗？")) {
              $(this).closest(".text").remove();
            }
          });
        });
      });
    </script>

    <script>
      $(document).ready(function () {
        $("#btn").click(function () {
          var tArea = $("textarea").val();
          var box = $("<div>", { class: "text" }).html(`
        <span>${tArea}</span>
        <div>
          <button>编辑</button>
          <a class="del">删除</a>
        </div>
      `);
          $("body").append(box);
        });

        // 将事件处理函数绑定到 document 上，而不是每次点击时
        $(document).on("click", ".del", function () {
          if (confirm("确定删除吗？")) {
            $(this).closest(".text").remove();
          }
        });
      });
    </script>
  </body>
</html>
